package com.hui.admin.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hui.admin.common.UserContext;
import com.hui.admin.common.enums.ErrorCodeEnum;
import com.hui.admin.common.exception.UserException;
import com.hui.admin.service.UserService;
import com.hui.admin.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * JWT 拦截器
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 Header 或 Parameter 获取 Token
        String token = request.getHeader("Authorization");

        if (StrUtil.isEmpty(token)) {
            token = request.getParameter("token");
        }

        // 如果没有提供 Token，拒绝访问
        if (StrUtil.isBlank(token)) {
            throw new UserException(ErrorCodeEnum.TOKEN_NOT_EXIST);
        }

        // TODO TOKEN 过期验证

        try {
            String username = JwtUtil.parseToken(token);
            // 假设 UserService 可以根据用户名查用户ID
            Long userId = userService.getUserIdByUsername(username);
            UserContext.setCurrentUserId(userId);
        } catch (Exception e) {
            // Token 解析失败，可能是签名错误、过期等
            throw new UserException(ErrorCodeEnum.TOKEN_PARSE_ERROR);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear(); // 清除线程变量，防止内存泄漏
    }
}

